package com.ay.controller;


import com.ay.entity.Tupian;
import com.ay.service.TupianService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.lang.model.element.NestingKind;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;



/**
 * @description: TODO
 * @return:
 * @author: 你的名字,your name,自己更改
 * @dateTime: 2021/5/31 21:48
 */
@Controller
@RequestMapping("/wenjian")
public class WenjianShangchuan {

    @Autowired
    TupianService tupianService;

    @RequestMapping("/zhanshi")
    public String findAll2(Model model) {

        return "zhanshi";
    }

    /*返回一个对象时*/
    @RequestMapping("/show")
    @ResponseBody
    public Tupian show() {
        return tupianService.select();
    }

/*返回对象集合时*/
    @RequestMapping(value = "/showAll")
    @ResponseBody
    public List<Tupian> findAll3(Model model) {
        return tupianService.selectall();
    }


    @GetMapping(value = "/shangchuan")
    public String findAll(Model model) {

        return "shangchuan";
    }






   /*上传单张图片*/
    @RequestMapping("/upload")
    public String fileUpload(@RequestParam("file") MultipartFile multipartFile,
                             HttpServletResponse response, HttpServletRequest request) throws IOException {

        String s = request.getServletContext().getRealPath("static");
        System.out.println(s);//E:\springdemo\wenjianup\target\static

        String s1 = request.getServletContext().getRealPath("resources");
        System.out.println(s1);//E:\springdemo\wenjianup\target\resources

        String s2 = request.getServletContext().getRealPath("images");
        System.out.println(s2);//E:\springdemo\wenjianup\target\images

        String s3 = request.getServletContext().getRealPath("aaaaaa");
        System.out.println(s3);//E:\springdemo\wenjianup\target\aaaaaa



        /*获取资源路径    target所在路径下的/WEB-INF/classes/ */
        //    String realPath = ResourceUtils.getURL("classpath:").getPath();
        String realPath = s1;

        String originalFilename = multipartFile.getOriginalFilename();//获取图片原始的名称
        System.out.println("=======我上传的图片名称是:" + originalFilename);

        long l = System.currentTimeMillis();//获取当前毫秒数
        String newName = l + originalFilename;
        System.out.println("=======毫秒数+原始名称:" + newName);

        InputStream inputStream = multipartFile.getInputStream();//输入流,用来读取图片

        System.out.println("路径" + realPath);

//在项目根目录下创建image文件夹.用来保存上传的图片
        File file = new File(realPath + "/image/");
        if (!file.exists()) {
            file.mkdirs();//如果这个文件不存在,创建文件夹
        }

        if (!multipartFile.isEmpty()) {
            FileOutputStream fos = new FileOutputStream(realPath + "/image/" + newName);
            int length = 0;
            while ((length = inputStream.read()) != -1) {
                fos.write(length);
            }
            fos.flush();
            fos.close();
            inputStream.close();

        } else {
            return "fail";
        }

        String contextPath = request.getContextPath();
        System.out.println(1111111111);
        System.out.println(contextPath);

        String url = contextPath+"/image/" + newName;
        Tupian tupian = new Tupian();
        tupian.setName(newName);
        tupian.setUrl(url);
        tupianService.insert(tupian);

        return "ok";
    }

    /*多文件上传****************************************************************************************/

    @RequestMapping("/uploads")
    public String fileUpload2(@RequestParam("file") MultipartFile[] multipartFile,
                              HttpServletResponse response, HttpServletRequest request) {
        //在项目根目录target下创建image文件夹.用来保存上传的图片
        String realPath = request.getServletContext().getRealPath("resources");

        System.out.println(realPath);
        File file = new File(realPath + "/image/");  //注意最后的/说明是文件夹
        if (!file.exists()) {
            file.mkdirs();//如果这个文件不存在,创建文件夹  注意mkdir 和 mkdirs的区别
        }



         int count=0;
        System.out.println(multipartFile);
        System.out.println(multipartFile.length);
        for (int i = 0; i <3 ; i++) {
            MultipartFile ffff = multipartFile[i];                  //判断文件对象是不是空的    注意是空的不代表是null
            if(ffff.isEmpty()){
                count++;
            }
        }
        System.out.println(count);

        //判断数组内容是否为空
        if (count<3) {

            for (int i = 0; i < multipartFile.length; i++) {
                MultipartFile ffff = multipartFile[i];    //遍历文件数组

                if (!ffff.isEmpty()) {
                    String originalFilename = ffff.getOriginalFilename();//获取图片原始的名称
                    long l = System.currentTimeMillis();//获取当前毫秒数
                    String newName = l + originalFilename;//使图片名字不重复

                    try {
                        ffff.transferTo(new File(realPath + "/image/" + newName));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    String contextPath = request.getContextPath();
                    System.out.println(contextPath);

                    String url = contextPath+"/image/" + newName;
                    Tupian tupian = new Tupian();   //这个new对象不能放外面 才能保存多张图片
                    tupian.setName(newName);         //放在外面就是一个对象 所有的图片会指向最后的对象地址
                    tupian.setUrl(url);
                    tupianService.insert(tupian);
                }
            }
            return "ok";
        }
        return "fail";
    }

    /*文件下载**********************************************************************************/

    @RequestMapping("/finddownload")
    public String finddownload(Model model){
        List<Tupian> list = tupianService.selectall();
        model.addAttribute("tupians",list);
        return "download";
    }

/*文件下载  以流的形式响应  并提示浏览器这是下载流  就可以了*/

    @ResponseBody
    @RequestMapping("/download")
    public void download(HttpServletRequest request,HttpServletResponse response){

        String name = request.getParameter("name");
        System.out.println(name);


                    //war包的真实路径
        String url = request.getServletContext().getRealPath("resources")+"/image/";
        System.out.println(url);

        File file = new File(url);
        try {
            FileInputStream is = new FileInputStream(new File(file,name));


            //通知浏览器这是文件下载流
            response.setContentType("application/octet-stream; charset=utf-8");

            /*java.net.URLEncoder.encode(name,"UTF-8"));图片的中文名可以下载显示*/
            response.setHeader("Content-Disposition", "attachment; filename="+java.net.URLEncoder.encode(name,"UTF-8"));


                ServletOutputStream out= response.getOutputStream();
                byte[] buffer=new byte[1024];
                int len=-1;
                while((len=is.read(buffer))!=-1){
                    out.write(buffer,0,len);
                }
                out.close();
                is.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }

    }

}


